package com.linchong.concurrency.deadLock;

import com.linchong.concurrency.annoations.ThreadSafe;
import lombok.extern.slf4j.Slf4j;

/**
 * @author linchong
 * @version 1.0
 * @Date: 2020-12-09 13:25
 * @Description: DeadLock$
 * 当deadlock类对象flag==1（td1）时，先锁定o1,睡眠500ms
 * 而td1睡眠是，另外一个flag==0对象（td2）线程启动，先锁定o2,睡眠500ms
 * td1睡眠结束后需要锁定o2才能继续执行，而此时o2已被td2锁定
 * td2睡眠结束后需要锁定o1才能继续执行，而此时o1已被td1锁定
 * td1、td2相互等待，都需要得到对方锁定的资源才能继续执行，造成死锁
 *
 * 同时对o1加锁或同时对o2加锁
 * 加锁，尝试获取锁时，加上时间，超过时间，放弃锁请求并释放自己占用的锁
 */
@Slf4j
public class DeadLock implements Runnable {

	public int flag = 1;

	//静态对象是类的所有对象共享的
	private static Object o1 = new Object(), o2 = new Object();

	@Override
	public void run() {
		log.info("flag:{}", flag);
		if (flag == 1) {
			synchronized (o1) {
				try {
					Thread.sleep(500);
				} catch (Exception e) {
					e.printStackTrace();
				}
				synchronized (o2) {
					System.out.println("1");
				}
			}
		}
		if (flag == 0) {

			synchronized (o2) {
				try {
					Thread.sleep(500);
				} catch (Exception e) {
					e.printStackTrace();
				}
				synchronized (o1) {
					System.out.println("0");
				}
			}

		}
	}

	public static void main(String[] args) {
		DeadLock td1 = new DeadLock();
		DeadLock td2 = new DeadLock();
		td1.flag = 1;
		td2.flag = 0;

		new Thread(td1).start();
		new Thread(td2).start();
	}
}
